package com.neu.controller;


import com.neu.entity.*;
import com.neu.entity.DTO.ReviewReportDTO;
import com.neu.service.*;
import com.neu.base.PageBean;
import com.neu.base.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/review")
@Tag(name = "评审管理")
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ProgressRecordService progressRecordService;

    @Autowired
    private TenantService tenantService;

    @PostMapping("/getPage")
    @Parameters({
            @Parameter(name = "reviewerId", description = "评审员的id", required = true),
            @Parameter(name = "pageNum", description = "页码", required = true),
            @Parameter(name = "pageSize", description = "每页显示数量", required = true),
    })
    @Operation(summary = "分页")
    public Result page(@RequestParam String reviewerId,
                       @RequestParam Integer pageNum,
                       @RequestParam Integer pageSize){
        PageBean<Review> pagelist = reviewService.pagelist(pageNum, pageSize, reviewerId);
        //如果当前页码值大于总页数，返回最后一页数据
        if (pageNum > pagelist.getTotalPage()) {
            pagelist = reviewService.pagelist((int)pagelist.getTotalPage(), pageSize, reviewerId);
        }

        List<Review> reviewList = pagelist.getItems();

        List<ReviewReportDTO> dtoList = new ArrayList<>();
        List<Task> taskList = taskService.list();

        for (Review review : reviewList) {
            // 根据review中的projectId, taskId, reviewerId找到对应的对象
            Project project = projectService.getById(review.getProjectId());
            Task task = taskService.getById(review.getTaskId());
            User user = userService.getById(review.getReviewerId());

            Boolean flag = false;
            for (Task task1 : taskList) {
                if (task1.getProjectId().equals(project.getProjectId()) && task1.getTaskStatus().equals("2") && task1.getTaskType().equals("2")){
                    flag = true;
                }
            }
            if (!flag){
                continue;
            }

            // 创建DTO对象并填充数据
            ReviewReportDTO dto = new ReviewReportDTO();
            dto.setProjectId(project.getProjectId());
            dto.setProjectName(project.getProjectName());
            dto.setDueTime(task.getDueDate());
            dto.setCreateTime(task.getCreateTime());
            dto.setUserName(user.getUsername());
            dto.setTaskStatus(task.getTaskStatus());
            dto.setProjectStatus(project.getProjectStatus());
            dto.setReviewId(review.getReviewId());

            // 添加到列表中
            dtoList.add(dto);
        }

        PageBean<ReviewReportDTO> dtoPageBean = new PageBean<>(pagelist.getCurrentPage(), pagelist.getPageSize(),
                pagelist.getTotalNum(), dtoList);
        return Result.success(dtoPageBean);
    }

    @PostMapping(
            "/getProject"
    )
    @Parameters({
            @Parameter(name = "projectId", description = "项目的id", required = true),
    })
    @Operation(summary = "获取项目信息")
    public Result project(@RequestParam String projectId){
        Project project = projectService.getById(projectId);
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("project", project);
        resultData.put("username", tenantService.getById(project.getTenantId()).getTenantName());

        return Result.success(resultData);
    }

    @PostMapping("/search")
    @Operation(summary = "搜索评审")
    public Result search(
            @RequestBody Map map){

        PageBean<ReviewReportDTO> pagelist = reviewService.search(map);
        return Result.success(pagelist);
    }

    @PostMapping("/commit")
    @Parameters({
            @Parameter(name = "reviewId", description = "评审的id", required = true),
            @Parameter(name = "prompt", description = "提示哪个评审部分的字段", required = true),
            @Parameter(name = "text", description = "评审文字内容", required = true)
    })
    @Operation(summary = "提交评审")
    public Result commit(@RequestParam String reviewId,
                         @RequestParam String prompt,
                         @RequestParam String text){
        Review review = reviewService.getById(reviewId);
        Integer progress = null;
        System.out.println("\n\n\n");
        System.out.println(text);
        System.out.println("\n\n\n");
        if (prompt.equals("information_review")){
            review.setInformationReview(text);
            progress = 25;
        } else if (prompt.equals("function_review")) {
            review.setFunctionReview(text);
            progress = 50;
        }else if(prompt.equals("cost_review")){
            review.setCostReview(text);
            progress = 75;
        }else if(prompt.equals("comment")){
            review.setComment(text);
            progress = 100;
        }

        reviewService.updateById(review);

        Task reviewTask = taskService.getById(review.getTaskId());
        reviewTask.setProgress(progress);
        if (progress == 100){
            reviewTask.setTaskStatus("2");
            Project project = projectService.getById(review.getProjectId());
            project.setProjectStatus("2");
            project.setUpdateTime(LocalDateTime.now());
            projectService.updateById(project);
        } else {
            reviewTask.setTaskStatus("1");
        }

        reviewTask.setUpdateTime(LocalDateTime.now());
        taskService.updateById(reviewTask);

        ProgressRecord pr = new ProgressRecord();
        pr.setTaskId(reviewTask.getTaskId());
        pr.setProgress(progress);
        pr.setRecordTime(LocalDateTime.now());

        boolean success = progressRecordService.save(pr);

        if(!success){
            return Result.error("提交失败");
        }
        return Result.success("提交成功");
    }
}
